package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "id不能为空");
        }
        dto.checkParam();
        //执行分页条件
        IPage pageReq = new Page(dto.getPage(), dto.getSize());
        //执行查询条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery();
        if (dto.getStatus() != null) {
            queryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> pageResult = page(pageReq, queryWrapper);
        //封装返回结果
        return new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal(),pageResult.getRecords());
    }

    @Autowired
    ApUserMapper apUserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateStatusById(AuthDto dto, Short status) {

        //检查参数
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"id不能为空");
        }
        if (status == null || (!status.equals(AdminConstants.FAIL_AUTH) && !status.equals(AdminConstants.PASS_AUTH))) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"状态异常");
        }
        //根据id查询实名认证信息
        ApUserRealname realname = getById(dto.getId());
        if (realname == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证信息不存在");
        }
        //判断实名认证信息的状态
        if (realname.getStatus().equals(AdminConstants.WAIT_AUTH)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ERROR,"实名认证信息状态异常");
        }
        //根据实名认证关联userId 查询出ap_user信息
        ApUser apUser = apUserMapper.selectById(realname.getUserId());
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证关联用户信息不存在");
        }
        //修改当前实名信息状态
        realname.setUpdatedTime(new Date());
        realname.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            realname.setReason(dto.getMsg());
        }
        updateById(realname);
        //判断是否为审核通过
        if (status.equals(AdminConstants.PASS_AUTH)) {
            //开通自媒体账户
            WmUser wmUser = createWmUser(apUser);
            //创建作者信息
            createAuthor(apUser, wmUser);
        }
        return null;

    }

    @Autowired
    ArticleFeign articleFeign;

    //创建作者信息
    private void createAuthor(ApUser apUser, WmUser wmUser) {
        ResponseResult<ApAuthor> apAuthorResult = articleFeign.findByUserId(apUser.getId());
        if (apAuthorResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, apAuthorResult.getErrorMessage());
        }
        ApAuthor author = apAuthorResult.getData();
        if (author != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "该作者信息已经存在");
        }
        author = new ApAuthor();
        author.setName(apUser.getName());
        author.setType(2);
        author.setUserId(apUser.getId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());
        ResponseResult saveResult = articleFeign.save(author);
        if (saveResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, saveResult.getErrorMessage());
        }
    }

    //开通自媒体账户
    @Autowired
    WemediaFeign wemediaFeign;

    private WmUser createWmUser(ApUser apUser) {
        //先查询是否开通账户
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (result.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, result.getErrorMessage());
        }
        //如果没有开通，则创建WmUser
        WmUser wmUser = result.getData();
        if (wmUser != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "该自媒体账户已经存在");
        }
        //保存WmUser
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if (saveResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, saveResult.getErrorMessage());
        }
        return saveResult.getData();
    }






}
